package cn.ydt.ydt.shopping.webapi.service.impl;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.pojo.work.dto.WorkDTO;
import cn.ydt.ydt.shopping.webapi.utils.SecurityContextUtils;
import cn.ydt.ydt.pojo.shopping.dto.SimpleDailyDTO;
import cn.ydt.ydt.pojo.shopping.model.DailyUseOrder;
import cn.ydt.ydt.pojo.shopping.vo.SimpleDailyVO;
import cn.ydt.ydt.shopping.service.IDailyService;
import cn.ydt.ydt.shopping.webapi.mapper.DailyMapper;
import io.netty.handler.codec.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.IWorkService;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class DailyServiceImpl implements IDailyService {



    @Autowired
    DailyMapper dailyMapper;

    @DubboReference
    IWorkService workService;



    @Override
    public void AddDailyOrder(SimpleDailyDTO simpleDailyDTO) {
        //判断订单内容是否为空
        if (simpleDailyDTO == null||simpleDailyDTO.getDailyUseInformation()==null || simpleDailyDTO.getWorkAddress() == null){
            log.warn("用品订单信息为空，抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"用品订单为空");
        }
        log.info("创建日用品订单类,并把传过来的值赋给这个类");
        DailyUseOrder dailyUseOrder = new DailyUseOrder();
        BeanUtils.copyProperties(simpleDailyDTO,dailyUseOrder);
        log.info("补全剩余的信息");
        LocalDateTime dateTime = LocalDateTime.now();
        dailyUseOrder.setCreateTime(dateTime);
        dailyUseOrder.setModifyTime(dateTime);
        dailyUseOrder.setIsDelete((byte)0);
        dailyUseOrder.setIsComplete((byte)0);
        dailyUseOrder.setUserId(SecurityContextUtils.getUserId());
        dailyUseOrder.setAddress(simpleDailyDTO.getWorkAddress());
        log.info("对应用户id为：{}",SecurityContextUtils.getUserId());
        //把订单信息添加到数据库
        log.info("添加订单信息到数据库{}",simpleDailyDTO);
        dailyMapper.insertDaily(dailyUseOrder);
        log.info("订单添加完成");
        log.info("调用任务模块添加任务");
        WorkDTO workDTO = new WorkDTO();
        workDTO.setWorkName("日用品购买");
        workDTO.setWorkInfo(simpleDailyDTO.getDailyUseInformation());
        workDTO.setWorkAddress(simpleDailyDTO.getWorkAddress());
        workService.addNewWork(workDTO);
    }

    @Override
    public List<SimpleDailyVO> getDailyByUserId() {
        Long userId = SecurityContextUtils.getUserId();
        log.info("判断传递过来的id是否为空");
        if (userId == null){
            log.warn("id为空抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"请求的userId为空");
        }
        log.info("返回查询结果");
        return dailyMapper.getDailyOrderByUserId(userId);
    }


}
